package su.base.module;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import su.security.entity.SecurityModule;
import su.security.entity.SecurityUrl;
import su.security.entity.SecurityUser;
import su.security.service.SecurityModuleService;
import su.security.service.SecurityUrlService;
import su.security.service.SecurityUserService;
import su.tool.SuIntUtils;
/**
 * 项目基本权限管理（修改密码、退出等操作）
 * @author SuShimeng
 *
 */
@Controller
@RequestMapping("/admin/security")
public class SecurityAdminServlet {

	@Autowired
	private SecurityUserService securityUserService;

	@Autowired
	private SecurityModuleService securityModuleService;

	@Autowired
	private SecurityUrlService securityUrlService;

	protected final Log log = LogFactory.getLog(getClass());
	/**
	 * 权限首页
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("index")
	public String index(HttpServletRequest request, Model model){
		return "frame/index";
	}
	
	/**
	 * 退出
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request, Model model){
		request.getSession().setAttribute("sessionUser", null);
		return "login";
	}

	/**
	 * 修改密码
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("do_update_pwd")
	public String doUpdatePwd(HttpServletRequest request, Model model){
		Object o = request.getSession().getAttribute("sessionUser");
		if(o==null)return "login";
		String res = "";
		try {
			securityUserService.updatePwd(((SecurityUser)o).getUsername(), request.getParameter("userpwd"), request.getParameter("newpwd"));
		} catch (Exception e) {
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res))return "/admin/updatepwd.jsp?sumsg="+res;
		return "redirect:/updatepwd.jsp?sumsg=修改成功";
	}
	/**
	 * 管理员密码重置
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("do_reset_pwd")
	public void doResetPwd(HttpServletRequest request,HttpServletResponse response, Model model) {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			log.error(e1.getMessage());
		}
		String res = "";
		try {
			securityUserService.operateResetPwd("123", SuIntUtils.getInt(request.getParameter("userId")));
		} catch (Exception e) {
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res))out.println(res);
		else out.println("密码重置成功，默认密码123");
	}
	/**
	 * 后台管理页面top
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("top")
	public String top(HttpServletRequest request, Model model) {
		Object o = request.getSession().getAttribute("sessionUser");
		if(o==null)return "redirect:/admin/security/index.action";
		SecurityUser u = (SecurityUser)o;
		SecurityUser user = securityUserService.getBaseinfo(u.getId());
		if(user==null){
			request.setAttribute("errorCode", "连接超时，请重新登录");
			return "su_error";
		}
		List<SecurityModule> modules = securityModuleService.getModuleList(user.getModuleids());
		if(modules == null || modules.isEmpty()){
			request.setAttribute("errorCode", "当前用户还没有分配任何管理权限，请联系管理员");
			return "su_error";
		}
		
		List<Map> apps = new ArrayList<Map>();
		for(SecurityModule mo : modules){
			Map m = new HashMap();
			m.put("appId", mo.getId());
			m.put("appText", mo.getModulename());
			apps.add(m);
		}
		
		request.setAttribute("apps", apps);
		return "frame/top";
	}
	/**
	 * 后台管理页面left
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("left")
	public String left(HttpServletRequest request, Model model){
		String appId = request.getParameter("appId");
		if(StringUtils.isBlank(appId))return "frame/left";
		SecurityModule module = securityModuleService.getBaseinfo(SuIntUtils.getInt(appId));
		if(module==null){
			request.setAttribute("errorCode", "ID为"+appId+"的模块设置有误，请联系管理员");
			return "su_error";
		}
		List<SecurityUrl> us = securityUrlService.getUrlList(module.getUrlids());
		if(us==null || us.isEmpty()){
			request.setAttribute("errorCode", "ID为"+appId+"的模块设置有误，请联系管理员");
			return "su_error";
		}
		List<Map> urls = new ArrayList<Map>();
		Map m;
		for(SecurityUrl u : us){
			m = new HashMap();
			m.put("urlText", u.getUrlname());
			m.put("urlPath", u.getUrl());
			urls.add(m);
		}
		
		request.setAttribute("urls", urls);
		return "frame/left";
	}
	
}
